package com.zhaodui.util;

import com.wxapi.WxApiCall.WxApiCall;
import com.wxapi.model.RequestModel;
import com.zhaodui.basesys.entity.FxjOrderNoEntity;
import com.zhaodui.fxjwf.entity.FxjSysWfEntity;
import com.zhaodui.gps.entity.FxjLoanGpsEntity;
import com.zhaodui.loan.entity.FxjLoanFkEntity;
import com.zhaodui.loan.entity.FxjLoanInsEntity;
import com.zhaodui.loan.entity.FxjLoanMaEntity;
import com.zhaodui.order.entity.FxjOrderLoanEntity;
import com.zhaodui.order.entity.FxjOrderMainEntity;
import com.zhaodui.order.entity.FxjOrderObjEntity;
import com.zhaodui.order.page.FxjOrderMainPage;
import com.zhaodui.order.service.FxjOrderMainServiceI;
import com.zhaodui.pl.entity.FxjPlReplanEntity;
import com.zhaodui.pro.entity.FxjProMainEntity;
import com.zhaodui.sys.entity.FxjOtherLoginEntity;
import com.zhaodui.tongdun.BodyGuardApiInvoker;
import com.zhaodui.tongdun.BodyGuardApiResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSType;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.TSUserOrg;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Validator;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.xiaoleilu.hutool.date.DateTime.now;


public class fxjUtil {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(fxjUtil.class);


	@Autowired
	private Validator validator;
	/*
	生成融资物管理
	 */
	public static boolean genLoanMa(String    orderNoin){
		SystemService systemService =ApplicationContextUtil.getContext().getBean(SystemService.class);

		boolean result = false;
		FxjOrderMainEntity fxjOrderMain = systemService.findUniqueByProperty(FxjOrderMainEntity.class,"orderNo", orderNoin);
		if (fxjOrderMain != null){
			String orderNo = fxjOrderMain.getOrderNo();
			FxjLoanMaEntity fxjLoanMaEntity  = systemService.findUniqueByProperty(FxjLoanMaEntity.class, "orderNo", orderNo);
			if(fxjLoanMaEntity == null){
				fxjLoanMaEntity = new FxjLoanMaEntity();
				fxjLoanMaEntity.setMaBy1("N");
				fxjLoanMaEntity.setMaBy2("N");
			}
			fxjLoanMaEntity.setOrderNo(orderNo);
			fxjLoanMaEntity.setCarNo(fxjOrderMain.getConNo());
			fxjLoanMaEntity.setCarVin(fxjOrderMain.getCarVin());
			fxjLoanMaEntity.setCusName(fxjOrderMain.getCusName());
			fxjLoanMaEntity.setBpmStatus("1");

			fxjLoanMaEntity.setGuohuUser(fxjOrderMain.getGuohuUser());
			fxjLoanMaEntity.setDiyaUser(fxjOrderMain.getDiyaUser());
			fxjLoanMaEntity.setSysOrgCode(fxjOrderMain.getSysOrgCode());
			systemService.saveOrUpdate(fxjLoanMaEntity);

			result = true;
		}

		FxjLoanGpsEntity fxjLoanGpsEntity = systemService.findUniqueByProperty(FxjLoanGpsEntity.class,"orderNo", orderNoin);
		if (fxjLoanGpsEntity != null){
			String orderNo = fxjOrderMain.getOrderNo();
			FxjLoanGpsEntity FxjLoanGpsEntity  = systemService.findUniqueByProperty(FxjLoanGpsEntity.class, "orderNo", orderNo);
			if(fxjLoanGpsEntity == null){
				fxjLoanGpsEntity = new FxjLoanGpsEntity();
				fxjLoanGpsEntity.setGpsStatus("N");

			}
			fxjLoanGpsEntity.setOrderNo(orderNo);
			fxjLoanGpsEntity.setCarNo(fxjOrderMain.getConNo());
			fxjLoanGpsEntity.setCarVin(fxjOrderMain.getCarVin());
			fxjLoanGpsEntity.setCusName(fxjOrderMain.getCusName());
			fxjLoanGpsEntity.setBpmStatus("1");
			fxjLoanGpsEntity.setInstallUser(fxjOrderMain.getGpsUser());
			fxjLoanGpsEntity.setSysOrgCode(fxjOrderMain.getSysOrgCode());
			systemService.saveOrUpdate(fxjLoanGpsEntity);

			result = true;
		}


		return result;
	}
	/*
	生成保险管理
	 */
	public static boolean genLoanIns(String    orderNoin){
		SystemService systemService =ApplicationContextUtil.getContext().getBean(SystemService.class);
		boolean result = false;
		FxjOrderMainEntity fxjOrderMain = systemService.findUniqueByProperty(FxjOrderMainEntity.class,"orderNo", orderNoin);
		if (fxjOrderMain != null){
			String orderNo = fxjOrderMain.getOrderNo();
			FxjLoanInsEntity fxjLoanInsEntity  = systemService.findUniqueByProperty(FxjLoanInsEntity.class, "orderNo", orderNo);
			if(fxjLoanInsEntity == null){
				fxjLoanInsEntity = new FxjLoanInsEntity();
				fxjLoanInsEntity.setBpmStatus("1");
				fxjLoanInsEntity.setSysOrgCode(fxjOrderMain.getSysOrgCode());
			}
			fxjLoanInsEntity.setOrderNo(orderNo);
			fxjLoanInsEntity.setCusName(fxjOrderMain.getCusName());
			fxjLoanInsEntity.setCusMobile(fxjOrderMain.getCusMobile());
			systemService.saveOrUpdate(fxjLoanInsEntity);
			result = true;
		}
		return result;
	}

	public static  String getdictname(String TypeGroup,String TypeCode){
		String TypeName="";
		List<TSType> task  = ResourceUtil.getCacheTypes(TypeGroup.toLowerCase());
		for(TSType t:task){
			if(TypeCode.equals(t.getTypecode())){
				TypeName =  t.getTypename();
				break;
			}
		}
		return  TypeName;
	}
	public static  boolean changeBpmstatus(String  orderNo,String bpmStatus){
		SystemService systemService =ApplicationContextUtil.getContext().getBean(SystemService.class);
		FxjOrderMainServiceI fxjOrderMainService =ApplicationContextUtil.getContext().getBean(FxjOrderMainServiceI.class);

		boolean result = false;
		FxjLoanFkEntity fxjLoanFkEntity  = systemService.findUniqueByProperty(FxjLoanFkEntity.class, "orderNo", orderNo);
		if (fxjLoanFkEntity!=null){
			fxjLoanFkEntity.setBpmStatus(bpmStatus);
			systemService.updateEntitie(fxjLoanFkEntity);
		}
		FxjLoanInsEntity fxjLoanInsEntity  = systemService.findUniqueByProperty(FxjLoanInsEntity.class, "orderNo", orderNo);

		if(fxjLoanInsEntity != null){
			fxjLoanInsEntity.setBpmStatus(bpmStatus);
			systemService.updateEntitie(fxjLoanInsEntity);
		}
		FxjLoanMaEntity fxjLoanMaEntity  = systemService.findUniqueByProperty(FxjLoanMaEntity.class, "orderNo", orderNo);
		if(fxjLoanMaEntity != null){
			fxjLoanMaEntity.setBpmStatus(bpmStatus);
			systemService.updateEntitie(fxjLoanMaEntity);
		}

		FxjOrderMainEntity fxjOrderMain = fxjOrderMainService.findUniqueByProperty(FxjOrderMainEntity.class,"orderNo", orderNo);
		try {
			fxjOrderMain.setBpmStatus(bpmStatus);
			systemService.updateEntitie(fxjOrderMain);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return  result;
	}


    /*
    生成放款列表
     */
	public static boolean genLoanFK(String    orderNoin){
		SystemService systemService =ApplicationContextUtil.getContext().getBean(SystemService.class);

		boolean result = false;
		FxjOrderMainEntity fxjOrderMain = systemService.findUniqueByProperty(FxjOrderMainEntity.class,"orderNo", orderNoin);
		if (fxjOrderMain != null){
			String orderNo = fxjOrderMain.getOrderNo();
			FxjProMainEntity fxjProMainEntity = systemService.findUniqueByProperty(FxjProMainEntity.class,"proNo",fxjOrderMain.getProNo());
			FxjLoanFkEntity fxjLoanFkEntity  = systemService.findUniqueByProperty(FxjLoanFkEntity.class, "orderNo", orderNo);
			if(fxjLoanFkEntity == null){
				fxjLoanFkEntity = new FxjLoanFkEntity();
				fxjLoanFkEntity.setBpmStatus("1");
				fxjLoanFkEntity.setSysOrgCode(fxjOrderMain.getSysOrgCode());
			}
			fxjLoanFkEntity.setOrderNo(orderNo);
			fxjLoanFkEntity.setCusName(fxjOrderMain.getCusName());
			fxjLoanFkEntity.setCusMobile(fxjOrderMain.getCusMobile());
			fxjLoanFkEntity.setLoanAmount(fxjOrderMain.getOrderAmount());
			fxjLoanFkEntity.setLoanPeriod(fxjOrderMain.getOrderPeriod());
			if(fxjProMainEntity!=null){
				fxjLoanFkEntity.setLoanDbmonth(fxjProMainEntity.getProDepositRatio());
				fxjLoanFkEntity.setLoanMonth(fxjProMainEntity.getProCreditingRate());

			}
			systemService.saveOrUpdate(fxjLoanFkEntity);
			result = true;
		}
		return result;
	}


	public static String getNextomNoticeId(String orderType){
		SystemService systemService =ApplicationContextUtil.getContext().getBean(SystemService.class);
		Map<String, Object> countMap = systemService
				.findOneForJdbc("SELECT count(*)+1 as count FROM fxj_order_no  t where  TO_DAYS(t.create_date) = TO_DAYS(NOW());");
		String noticeid = null;
			noticeid = "DD"
					+ DateUtils.date2Str(new Date(), DateUtils.yyyyMMdd)
					+ "-"
					+ StringUtil.leftPad(
					((Long) countMap.get("count")).intValue(), 4,
					'0');
		FxjOrderNoEntity fxjOrderNoEntity = new FxjOrderNoEntity();
		fxjOrderNoEntity.setCreateDate(now());
		systemService.save(fxjOrderNoEntity);
		return  noticeid;
	}

	public static String getNextfileId(String orderType){
		SystemService systemService =ApplicationContextUtil.getContext().getBean(SystemService.class);
		Map<String, Object> countMap = systemService
				.findOneForJdbc("SELECT count(*)+1 as count FROM fxj_file_main  t where  TO_DAYS(t.create_date) = TO_DAYS(NOW());");
		String noticeid = null;
		noticeid = "FILE"
				+ DateUtils.date2Str(new Date(), DateUtils.yyyyMMdd)
				+ "-"
				+ StringUtil.leftPad(
				((Long) countMap.get("count")).intValue(), 4,
				'0');
		return  noticeid;
	}

	/*
生成还款计划表
*/
	public static FxjSysWfEntity getwf(String  prowf, String step){
		SystemService systemService =ApplicationContextUtil.getContext().getBean(SystemService.class);
		FxjSysWfEntity fxjSysWfEntity = new FxjSysWfEntity();
			List<FxjSysWfEntity> listwf = systemService.findByProperty(FxjSysWfEntity.class,"wfNo",prowf);
				for(FxjSysWfEntity tn: listwf ) {
					if (step.equals(tn.getWfNowStep())) {
						fxjSysWfEntity = tn;
					}
				}
		return fxjSysWfEntity;
	}
/*
   生成还款计划表
    */
	public static FxjSysWfEntity genwf(String  orderNoin,String orderOper){
		SystemService systemService =ApplicationContextUtil.getContext().getBean(SystemService.class);
		FxjOrderMainEntity fxjOrderMain = systemService.findUniqueByProperty(FxjOrderMainEntity.class, "orderNo", orderNoin);
		FxjSysWfEntity fxjSysWfEntity = new FxjSysWfEntity();
		String nowstep="1";
		String nextstep="1";

		if (fxjOrderMain != null){
 			List<FxjSysWfEntity> listwf = systemService.findByProperty(FxjSysWfEntity.class,"wfNo",fxjOrderMain.getProWf());
 			if("Y".equals(orderOper)){
				for(FxjSysWfEntity tn: listwf ){
					if(fxjOrderMain.getBpmStatus().equals(tn.getWfNowStep())){
						nextstep = tn.getWfNextStep();
					}
				}
				for(FxjSysWfEntity tnxt: listwf ){
					if(nextstep.equals(tnxt.getWfNowStep())){
						fxjSysWfEntity = tnxt;
					}
				}

			}
			if("N".equals(orderOper)){
				for(FxjSysWfEntity tn: listwf ){
					if(fxjOrderMain.getBpmStatus().equals(tn.getWfNowStep())){
						nextstep = tn.getWfBackStep();
					}
				}
				for(FxjSysWfEntity tnxt: listwf ){
					if(nextstep.equals(tnxt.getWfNowStep())){
						fxjSysWfEntity = tnxt;
					}
				}
			}
			if("R".equals(orderOper)){
                   nextstep="99";
                   for(FxjSysWfEntity tr: listwf ){
                   	if(nextstep.equals(tr.getWfNowStep())){
						fxjSysWfEntity = tr;
					}

				   }
			}
            if("A".equals(orderOper)){
                nextstep="999";
                for(FxjSysWfEntity tr: listwf ){
                    if(nextstep.equals(tr.getWfNowStep())){
                        fxjSysWfEntity = tr;
                    }

                }
            }
			if("S".equals(orderOper)){
				for(FxjSysWfEntity tn: listwf ){
					if(fxjOrderMain.getBpmStatus().equals(tn.getWfNowStep())){
						nextstep = tn.getWfNowStep();
					}
				}
				for(FxjSysWfEntity tnxt: listwf ){
					if(nextstep.equals(tnxt.getWfNowStep())){
						fxjSysWfEntity = tnxt;
					}
				}
			}
		}
		return fxjSysWfEntity;
	}
	/*
   生成还款计划表
    */
	public static boolean genRePlan(String  orderNoin){
		SystemService systemService =ApplicationContextUtil.getContext().getBean(SystemService.class);
		DecimalFormat    df   = new DecimalFormat("######0.00");
		String loanReMethod = "10";
		boolean result = false;
		FxjOrderMainEntity fxjOrderMain = systemService.findUniqueByProperty(FxjOrderMainEntity.class, "orderNo", orderNoin);
		if (fxjOrderMain != null){
			String orderNo = fxjOrderMain.getOrderNo();
//			FxjOrderObjEntity fxjOrderObjEntity  = systemService.findUniqueByProperty(FxjOrderObjEntity.class, "orderNo", orderNo);
			List<FxjPlReplanEntity> replanlist = systemService.findByProperty(FxjPlReplanEntity.class, "orderNo", orderNo);
			systemService.deleteAllEntitie(replanlist);
			replanlist = systemService.findByProperty(FxjPlReplanEntity.class, "orderNo", orderNo);
			long  objPeriod = 0;//期数
			Double refAmountfirst = 0.00;//第一次还款金额
			Double refAmount      = 0.00;//每月还款金额
			Double refAmountlast      = 0.00;//最后还款金额

			Double refAmountfirstlx = 0.00;//第一次利息
			Double refAmountlx      = 0.00;//每月利息
			Double refAmountlxlast      = 0.00;//最后利息

			Double refAmountfirstbj = 0.00;//第一次本金
			Double refAmountbj      = 0.00;//每月本金
			Double refAmountbjlast      = 0.00;//每月本金

			Double refsum = 0.00;  //总融资额
			Double objYearRatio = 0.00;  //月利率
			Double refsumqctemp = 0.00;  //期初融资额
			Double refsumsytemp = 0.00;  //剩余融资额
            String finame = getFiname(orderNo);
			if (replanlist.size()==0){
				FxjLoanFkEntity fxjLoanFkEntity  = systemService.findUniqueByProperty(FxjLoanFkEntity.class, "orderNo", orderNo);
				loanReMethod = fxjLoanFkEntity.getLoanReMethod();
				objPeriod = Long.parseLong(fxjLoanFkEntity.getLoanPeriod());

				refsum = Double.parseDouble(fxjLoanFkEntity.getLoanSum());
				objYearRatio = Double.parseDouble(fxjLoanFkEntity.getLoanMonth());
			if("10".equals(loanReMethod)){
				refAmount = Math.floor(refsum * objYearRatio /100 + refsum / objPeriod)   ;
				refAmountfirst = refsum + refsum*objYearRatio/100* objPeriod- refAmount*(objPeriod-1);
				refAmountlast = refAmount;

				refAmountlx = Math.floor(refsum * objYearRatio/100);
				refAmountfirstlx = refsum * objYearRatio*objPeriod/100 - refAmountlx*(objPeriod-1);
				refAmountlxlast =refAmountlx;

				refAmountbj = refAmount - refAmountlx;
				refAmountfirstbj =  refAmountfirst - refAmountfirstlx;
				refAmountbjlast  = refAmountbj;
			}
			if("20".equals(loanReMethod)){
				refAmount = Math.floor(refsum * objYearRatio /100 )   ;
				refAmountfirst =  refsum*objYearRatio/100* objPeriod- refAmount*(objPeriod-1);
				refAmountlast = refAmount + refsum;

				refAmountlx = Math.floor(refsum * objYearRatio/100);
				refAmountfirstlx = refsum * objYearRatio*objPeriod/100 - refAmountlx*(objPeriod-1);
				refAmountlxlast =refAmountlx;

				refAmountbj = 0.00;
				refAmountfirstbj =  0.00;
				refAmountbjlast  = refsum;

			}
				for(int i =1;i<=objPeriod;i++){
					FxjPlReplanEntity fxjPlReplan = new FxjPlReplanEntity();
					fxjPlReplan.setOrderNo(orderNo);
					fxjPlReplan.setBpmStatus("1");
					fxjPlReplan.setSysOrgCode(fxjOrderMain.getSysOrgCode());
					fxjPlReplan.setCreateDate(now());
					fxjPlReplan.setCusName(fxjOrderMain.getCusName());
					fxjPlReplan.setOrderInfo(finame);
					fxjPlReplan.setProClass(fxjOrderMain.getProClass());
					fxjPlReplan.setProType(fxjOrderMain.getProType());
					fxjPlReplan.setRefTotalPeriod(Long.toString(objPeriod));
					fxjPlReplan.setRefPeriod(Long.toString(i));
					if(i==1){
						refsumqctemp = refsum;
						refsumsytemp = refsumqctemp -refAmountfirstbj;
						fxjPlReplan.setRefAmount(df.format(refAmountfirst));
						fxjPlReplan.setRefLixi(df.format(refAmountfirstlx));
						fxjPlReplan.setRefSybenjin(df.format(refsumsytemp));
						fxjPlReplan.setRefFbenjin(df.format(refsumqctemp));
						fxjPlReplan.setRefDate(DateUtils.date2Str(fxjLoanFkEntity.getLoanDate(),DateUtils.date_sdf));
						refsumqctemp = refsumsytemp;

					}else if(i==objPeriod){
						refsumqctemp = refsum;
						refsumsytemp = refsumqctemp -refAmountbjlast;
						fxjPlReplan.setRefAmount(df.format(refAmountlast));
						fxjPlReplan.setRefLixi(df.format(refAmountlxlast));
						fxjPlReplan.setRefSybenjin(df.format(refsumsytemp));
						fxjPlReplan.setRefFbenjin(df.format(refsumqctemp));
						fxjPlReplan.setRefDate(DateUtils.date2Str(fxjLoanFkEntity.getLoanDate(),DateUtils.date_sdf));
						fxjPlReplan.setBpmStatus("已还款");
						refsumqctemp = refsumsytemp;

					} else{
      					refsumsytemp = refsumqctemp -refAmountbj;
						fxjPlReplan.setRefAmount(Double.toString(refAmount));
						fxjPlReplan.setRefDate(DateUtils.date2Str(DateUtils.subMonth(fxjLoanFkEntity.getLoanDate(),i-1),DateUtils.date_sdf));
						fxjPlReplan.setRefLixi(Double.toString(refAmountlx));
						fxjPlReplan.setRefSybenjin(Double.toString(refsumsytemp));
						fxjPlReplan.setRefFbenjin(Double.toString(refsumqctemp));
						refsumqctemp = refsumsytemp;
					}


					systemService.save(fxjPlReplan);
					result = true;
				}
			}
		}
		return result;
	}

    /*
    获取融资物名称
     */
	private static String getFiname(String orderNo){
		SystemService systemService =ApplicationContextUtil.getContext().getBean(SystemService.class);

		ArrayList<FxjOrderLoanEntity>  loanList = (ArrayList<FxjOrderLoanEntity>) systemService.findByProperty(FxjOrderLoanEntity.class,"orderNo",orderNo);
		String finameel = ResourceUtil.getConfigByName("fxj.finame");
		String finame = "";
		for (FxjOrderLoanEntity t:  loanList)
		{
			if (finameel.equals(t.getElementNo())){
				finame = t.getElementContent();
				break;
			}
		}
		return finame;
	}


	public static  TSUser getsysorgcode(String sysuser){
	SystemService systemService =ApplicationContextUtil.getContext().getBean(SystemService.class);
	try{
		FxjOtherLoginEntity fxjOtherLoginEntity = systemService.findUniqueByProperty(FxjOtherLoginEntity.class,"otherid",sysuser);
		  if (fxjOtherLoginEntity!=null){
			  sysuser = fxjOtherLoginEntity.getUsername();
		  }
	}catch (Exception e){

	}
	TSUser task = systemService.findUniqueByProperty(TSUser.class,"userName",sysuser);
	if(task==null){
		sysuser=ResourceUtil.getConfigByName("mini.user");
		task = systemService.findUniqueByProperty(TSUser.class,"userName",sysuser);
	}

	try{
		TSDepart tsDepart = systemService.get(TSDepart.class,task.getDepartid());
		if(tsDepart!=null){
			tsDepart.setSysOrgCode(tsDepart.getOrgCode());
			task.setCurrentDepart(tsDepart);
		}
	}catch (Exception e){

	}
	return  task;
}

}
